package com.xteam.web.controller;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

import com.tangkf.utils.CommonUtils;
import com.tangkf.utils.bean.BeanHelper;
import com.tangkf.utils.bean.ReqHelper;
import com.xteam.ecsystem.service.admin.SystemLogService;
import com.xteam.ecsystem.utils.ConstantLocation;
import com.xteam.purview.entities.PurviewType;
import com.xteam.purview.service.impl.PurviewTypeFace;
import com.xteam.utils.WebTools;
import com.xteam.web.Error;

public class TypeController extends PurViewController implements IController {

	PurviewTypeFace	face	= PurviewTypeFace.getInstance();

	public TypeController() {
	}

	@Autowired
	private SystemLogService logService;
	
	public ModelAndView delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType(JSON_TYPE);

		String[] ids = ReqHelper.getRequestStrings(request, "typeId[]");
		String lslUser = ReqHelper.getRequestString(request, "lslUser");
		String lslAddress = ReqHelper.getRequestString(request, "lslAddress");
		
		int r = face.delBatch(PurviewType.class, PurviewType.PROP_TYPEID, ids);
		
		this.logService.saveSystemLogs(lslUser, lslAddress, ConstantLocation.LOG_FUNTYPE_MGR, 
				"delBatch", ConstantLocation.LOG_DELETE, "PurviewType");

		Error er = r > 0 ? Error.create(r + "", "删除类别出错！") : Error.create();
		WebTools.writerJsonToResponse(response, er);
		return null;
	}

	public ModelAndView find(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType(JSON_TYPE);

		PrintWriter out = response.getWriter();
		String data = JSONArray.fromObject(face.queryAll(PurviewType.class)).toString();
		out.println(data);
		return null;
	}

	public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType(JSON_TYPE);
		
		String lslUser = ReqHelper.getRequestString(request, "lslUser");
		String lslAddress = ReqHelper.getRequestString(request, "lslAddress");
		String lslType = ConstantLocation.LOG_ADD;
		String lslMethod = "save";

		PurviewType fn = new PurviewType();
		BeanHelper.requestToBean(fn, request);
		int r	= 0;
		if (CommonUtils.isEmpty(fn.getTypeId())) {
			r	= face.save(fn);
		} else {
			r	= face.update(fn);
			lslType = ConstantLocation.LOG_MODIFY;
			lslMethod = "update";
		}
		
		this.logService.saveSystemLogs(lslUser, lslAddress, ConstantLocation.LOG_FUNTYPE_MGR, 
				lslMethod, lslType, "PurviewType");
		
		Error er	= r>0?Error.create(r+"", "保存类别出错！"):Error.create();
		WebTools.writerJsonToResponse(response, er);
		return null;
	}

}
